<?php
/**[文档模型]
 * @Author: happy
 * @Email:  976123967@qq.com
 * @Date:   2015-04-12 22:36:57
 * @Last Modified by:   Administrator
 * @Last Modified time: 2015-07-09 11:21:41
 */
namespace Admin\Logic;
use Think\Model;
use Think\Upload;
class ArticleLogic extends Model
{
	

	// 自动验证
	public $_validate = array(
		array('category_cid','/^[^0]\d*$/','请选择栏目',1,'regex',3),  
		array('article_title','require','标题不能为空',1,'regex',3),
		array('sort','require','请输入排序值',0,'regex',3),
		array('sort','/^\d+$/i','排序值只能是数字',0,'regex',3),
		array('click','require','请输入浏览次数',0,'regex',3),
		array('click','/^\d+$/i','浏览次数只能是数字',0,'regex',3),
	);

	// 自动完成
    // array(填充字段,填充内容,[填充条件,附加规则])
    protected $_auto = array (
        // 发布时间
        array('addtime','_addtime',3,'callback'),
        // 编辑时间
        array('edittime','time',3,'function'),
        // 属性
        array('flag','_flag',3,'callback'),
        // user_uid
		array('user_uid','_uid',1,'callback'),
    );

    // 发布时间
    public function _addtime($con)
    {
    	if(!$con)
    		return strtotime(date('Y-m-d'));
    	else
    		return strtotime($con);
    }


    // 用户uid
	public function _uid()
	{
		return session('user_id');
	}

    // 属性自动完成
	public function _flag()
	{
		$flag = I('post.flag');
		return $flag? implode(',', $flag):'';
	}

	/**
	 * [add_ext 添加扩展字段值]
	 * @param [type] $aid [description]
	 * @param [type] $cid [description]
	 */
	public function add_ext($aid,$cid)
	{
		$cur = D('Category','Logic')->get_one($cid);
		$mid = $cur['model_mid'];
		$model = D('Model','Logic')->get_one($mid);
		// 1获取附表名称
		$table = 'article_'.$model['name'];
		// 2获取字段数据
		$field = D('ModelField','Logic')->get_all($mid);
		$data = array();
		$data['article_aid'] = $aid;
		$strhtml = '';
		foreach($field as $k=>$v)
		{
			// 字段内容值初始化
			$value = '';

			if($v['fname']=='article_aid') continue; 
			// 8文件上传 9图片上传
			if($v['show_type']==8 || $v['show_type']==9)
			{

				$dir   = $v['show_type']==9?'image':'file';
				$type  = $v['show_type']==9?C('cfg_image'):C('cfg_file');
				$value = $this->upload_ext($v['fname'],$dir,$type);
				// 上传错误
				if($value===false)
					$value = '';
			}
			// 7是多选
			else if($v['show_type']==7)
			{
				$value = implode(',', $_POST[$v['fname']]);
			}
			else
			{
				// stripcslashes 处理引号被转义问题
				$value = stripcslashes($_POST[$v['fname']]);
			}
			if($v['show_type']==3)
			{
				$strhtml .=$value;
			}
			$data[$v['fname']] = $value;
		}
		M($table)->add($data);
		$this->check_upload($strhtml,$aid);
	}
	/**
	 * [update_ext 修改扩展字段值]
	 * @return [type] [description]
	 */
	public function update_ext($aid,$cid)
	{
		

		$cur = D('Category','Logic')->get_one($cid);
		$mid = $cur['model_mid'];
		$model = D('Model','Logic')->get_one($mid);
		// 1获取附表名称
		$table = 'article_'.$model['name'];
		// 2获取字段数据
		$field = D('ModelField','Logic')->get_all($mid);


		$data = array();
		// 关联字段
		$data['article_aid'] = $aid;
		$strhtml = '';
		foreach($field as $v)
		{
			// 字段内容值初始化
			$value = '';

			if($v['fname']=='article_aid') continue; 
			// 8文件上传 9图片上传
			if($v['show_type']==8 || $v['show_type']==9)
			{
				$dir = $v['show_type']==9?'image':'file';
				$type = $v['show_type']==9?C('cfg_image'):C('cfg_file');
				$value = $this->upload_ext($v['fname'],$dir,$type);
				// 上传错误
				if($value === false)
					continue;
				if($value == '')
					continue;

			}
			// 7是多选
			else if($v['show_type']==7)
			{
				$value = implode(',', $_POST[$v['fname']]);

			}
			else
			{
				// stripcslashes 处理引号被转义问题
				$value = stripcslashes($_POST[$v['fname']]);
			}
			if($v['show_type']==3)
			{
				$strhtml .=$value;
			}
			// 有内容更新
			
			$data[$v['fname']] = $value;
		}
		M($table)->where(array('article_aid'=>$aid))->save($data);
		$this->check_upload($strhtml,$aid);

		return true;
	}

	/**
	 * [upload_ext 上传附表中的文件和图片]
	 * @param  [type] $uploadname [description]
	 * @param  [type] $dir        [description]
	 * @param  [type] $type       [description]
	 * @return [type]             [description]
	 */
	public function upload_ext($uploadname,$dir,$type)
	{


		if(!empty($_FILES[$uploadname]['name']))
		{

			// 删除原来的文件
			$aid = I('post.aid');
			if($aid)
			{
				/***表名称***/ 
				$cid = I('post.category_cid');
				$cur = D('Category','Logic')->get_one($cid);
				$mid = $cur['model_mid'];
				$model = D('Model','Logic')->get_one($mid);
				$table = 'article_'.$model['name'];
				$file = M($table)->where(array('article_aid'=>$aid))->getField($uploadname);
				is_file($file) && unlink($file);
			}


			$upload = new Upload();             // 实例化上传类
			$upload->maxSize  = 314572800 ;     // 设置附件上传大小
			$upload->exts  = explode('|', C('cfg_file'));// 设置附件上传类型
			$upload->autoSub =false;            //不要自动创建子目录
			$upload->rootPath = './Data/Uploads/'; //设置上传根路径 这个系统不会自动创建
			$upload->savePath = 'image/'.date('Y').'/'.date('m').'/'.date('d').'/';
			if($info=$upload->uploadOne($_FILES[$uploadname]))
                return $upload->rootPath.$info['savepath'].$info['savename'];
			else	
            	return false;
		}
		return '';
	}

	/**
	 * [check_upload 添加修改文档时候，删除编辑器中的图片]
	 * @param  [type] $strhtml [description]
	 * @param  [type] $aid     [description]
	 * @return [type]          [description]
	 */
	public function check_upload($strhtml,$aid)
	{
		$db = D('Upload');
		$upload = $db->where(array('article_aid'=>$aid))->select();
		if($upload)
		{
			foreach($upload as $up)
			{
				$temppic =$up['path'].'/'.$up['name'].'.'.$up['ext'];
				$temppic = ltrim($temppic,'./');
	
				if(!strchr($strhtml,$temppic))
				{	
					is_file($temppic) && unlink($temppic);
					$db->delete($up['id']);
				}
			}
		}

	}

	
	/**
	 * [get_one_by_cid 获取单条数据只限于单页面]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function get_one_by_cid($cid)
	{
		return $this->where(array('category_cid'=>$cid))->find();
	}


	/**
	 * [get_one 获取单条数据]
	 * @param  [type] $aid [description]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function get_one($aid,$cid)
	{
		$cur = D('Category','Logic')->get_one($cid);
		$mid = $cur['model_mid'];
		$model = D('Model','Logic')->get_one($mid);
		// 1获取附表名称
		$table = 'article_'.$model['name'];
		$ext = M($table)->where(array('article_aid'=>$aid))->find();
		$data = $this->find($aid);
		return array_merge($data,$ext);
	}

	/**
	 * [get_all 所有数据]
	 * @param  [type] $map         [description]
	 * @param  [type] $order       [description]
	 * @param  [type] $sort        [description]
	 * @param  [type] $currentPage [description]
	 * @param  [type] $listRows    [description]
	 * @return [type]              [description]
	 */
	public function get_all($map,$order,$sort,$currentPage,$listRows)
	{
		$data = D('ArticleView')->where($map)->order($order.' '.$sort)->page($currentPage.','.$listRows)->select();
		return $data;
	}



	/**
	 * [_before_insert 插入前置方法]
	 * @param  [type] $data    [description]
	 * @param  [type] $options [description]
	 * @return [type]          [description]
	 */
	public function _before_insert(&$data,$options)
	{
		$pic = $this->alter_pic();
		if($pic!==false)
			$data['pic'] = $pic;
		$file = $this->alter_file();
		if($file!==false)
			$data['file'] = $file;
	}
	/**
	 * [_before_update 更新前置方法]
	 * @param  [type] $data    [description]
	 * @param  [type] $options [description]
	 * @return [type]          [description]
	 */
	public function _before_update(&$data,$options)
	{
		$aid = I('post.aid');
		$pic = $this->alter_pic($aid);
		if($pic)
			$data['pic'] = $pic;

		$file = $this->alter_file($aid);
		if($file)
			$data['file'] = $file;
	}


	/**
	 * [alter_pic 上传文档图片]
	 * @param  [type] $data    [description]
	 * @param  [type] $options [description]
	 * @return [type]          [description]
	 */
	public function alter_pic($aid=null)
	{
		if(!empty($_FILES['pic']['name']))
		{
			if($aid)
			{
				$pic =$this->where(array('aid'=>$aid))->getField('pic') ;
				is_file($pic) && unlink($pic);
			}
			
			//上传栏目图片
			$upload = new Upload();             // 实例化上传类
			$upload->maxSize  = 314572800 ;     // 设置附件上传大小
			$upload->exts  = explode('|', C('cfg_image'));// 设置附件上传类型
			$upload->autoSub =false;            //不要自动创建子目录
			$upload->rootPath = './Data/Uploads/'; //设置上传根路径 这个系统不会自动创建
			$upload->savePath = 'image/'.date('Y').'/'.date('m').'/'.date('d').'/';
			if($info=$upload->uploadOne($_FILES['pic']))
                return $upload->rootPath.$info['savepath'].$info['savename'];
			else	
            	return false;
		}
		return '';
	}

	/**
	 * [alter_file 上传附件]
	 * @param  [type] $data    [description]
	 * @param  [type] $options [description]
	 * @return [type]          [description]
	 */
	public function alter_file($aid=null)
	{
		if(!empty($_FILES['file']['name']))
		{
			if($aid)
			{
				$file =$this->where(array('aid'=>$aid))->getField('file') ;
				is_file($file) && unlink($file);
			}
			
			//上传文件
			$upload = new Upload();             // 实例化上传类
			$upload->saveName = array();
			$upload->maxSize  = 314572800 ;     // 设置附件上传大小
			$upload->exts  = explode('|', C('cfg_file'));// 设置附件上传类型
			$upload->autoSub =false;            //不要自动创建子目录
			$upload->rootPath = './Data/Uploads/'; //设置上传根路径 这个系统不会自动创建
			$upload->savePath = 'file/'.date('Y').'/'.date('m').'/'.date('d').'/';
			if($info=$upload->uploadOne($_FILES['file']))
                return $upload->rootPath.$info['savepath'].$info['savename'];
			else	
            	return false;
		}
		return '';
	}


	/**
	 * [_after_insert 添加后置方法]
	 * @param  [type] $data    [description]
	 * @param  [type] $options [description]
	 * @return [type]          [description]
	 */
	public function _after_insert($data,$options)
	{
		// 添加图片集合
		$isattr = I('post.isattr');
		if(!$isattr)
			D('ArticlePic',"Logic")->add_pic($data['aid']);
		else
			D('ArticlePic',"Logic")->add_attr_pic($data['aid']);
		
		
		// 更新编辑器上传的附件
		D('Upload','Logic')->update_uoload_attachment($data['aid']);
		D('ArticleAttr')->alert_article_attr($data['aid']);
		$this->set_url($data['aid']);
		
	}
	
	/**
	 * [_after_update 更新后置方法]
	 * @param  [type] $data    [description]
	 * @param  [type] $options [description]
	 * @return [type]          [description]
	 */
	public function _after_update($data,$options)
	{
		// 添加图片集合
		$isattr = I('post.isattr');
		if(!$isattr)
			D('ArticlePic',"Logic")->add_pic($data['aid']);
		else
			D('ArticlePic',"Logic")->add_attr_pic($data['aid']);
		
		// 更新编辑器上传的附件
		D('Upload','Logic')->update_uoload_attachment($data['aid']);
		D('ArticleAttr')->alert_article_attr($data['aid']);
		$this->set_url($data['aid']);
	
	}

	/**
	 * [del 删除]
	 * @param  [type] $data    [description]
	 * @param  [type] $options [description]
	 * @return [type]          [description]
	 */
	public function del($aid)
	{
		$aids = explode(',',$aid);
		$articlePicLogic = D('ArticlePic','Logic');
		$ArticleModel = D('Article');
		$categoryLogic = D('Category','Logic');
		$modelLogic = D('Model','Logic');
		$articleAttrModel = D('ArticleAttr');
		$uploadLogic = D('Upload','Logic');
		foreach($aids as $aid)
		{
			if($aid)
			{
				$cid = $ArticleModel->where(array('aid'=>$aid))->getField('category_cid');
			
				$cur = $categoryLogic->get_one($cid);
				$model = $modelLogic->get_one($cur['model_mid']);
				$table = 'article_'.$model['name'];
				M($table)->where(array('article_aid'=>$aid))->delete();
				$articlePicLogic->delete_pic_by_article_aid($aid);
				$articleAttrModel->where(array('article_aid'=>$aid))->delete();
				// 删除编辑器里的图片
				$uploadLogic->delete_upload_by_article_aid($aid);
				// 删除图集图片
				$articlePicLogic->delete_pic_by_article_aid($aid);
				$this->delete($aid);

				// 更新规则
				$article = include 'Data/Config/article.inc.php';
				if(isset($article[$aid]))
					unset($article[$aid]);
				file_put_contents('./Data/Config/article.inc.php', "<?php\n return ".var_export($article,true)."; ");

			}

		}
		return true;
	}

	/**
     * [del_attachment 删除附件]
     * @param  [type] $aid   [description]
     * @param  [type] $field [description]
     * @return [type]       [description]
     */
    public function del_attachment($aid,$field)
    {
	   $db = M('Article');
	   if($field=='pic' || $field=='file')
       {
       		$pic = $this->where(array('aid'=>$aid))->getField($field);
       		is_file($pic) && unlink($pic);
	        $db->save(array($field=>'','aid'=>$aid));
       }
	   else
	   {
	   	 	$cid = $db->where(array('aid'=>$aid))->getField('category_cid');
	        $cur = D('Category','Logic')->get_one($cid);
	        $model = D('Model','Logic')->get_one($cur['model_mid']);
	        $table = 'article_'.$model['name'];

	        $db = M($table);
	        $pic = $db->where(array('article_aid'=>$aid))->getField($field);
	        is_file($pic) && unlink($pic);
	       	$db->where(array('article_aid'=>$aid))->save(array($field=>''));
	   }
       return true;
    }

    /**
	 * [update_sort 更新排序]
	 * @param  [type] $aid   [description]
	 * @param  [type] $sort [description]
	 * @return [type]       [description]
	 */
	public function update_sort($aid,$sort)
	{

		foreach($aid as $k=>$v)
		{
			$this->save(array('sort'=>$sort[$k],'aid'=>$v));
		}
		return true;
	}


	/**
	 * [update_check_state 更新审核状态]
	 * @param  [type] $aid    [description]
	 * @param  [type] $status [description]
	 * @return [type]         [description]
	 */
    public function update_check_state($aid,$status)
    {
		foreach($aid as $k=>$v)
		{
			$this->save(array('verifystate'=>$status,'aid'=>$v));
		}
		return true;
    }


    public function update_flag($aids,$action)
    {
    	$flag = I('post.opa');

    	foreach($aids as $k=>$v)
		{
			// 把原先的属性取出
			$oldFlag = $this->where(array('aid'=>$v))->getField('flag');
			// 验证是否已经有属性存在
			if($action)
			{
				if(!strchr($oldFlag,$flag))
					$oldFlag .=','.$flag;
			}
			else
			{
				if(strchr($oldFlag,$flag))
					$oldFlag  = preg_replace('/(,)?'.$flag.'(,)?/', ',', $oldFlag);
			}
			$newFlag = trim($oldFlag,',');
			M('article')->save(array('flag'=>$newFlag,'aid'=>$v));
		}
		return true;
    }


    public function set_url($aid)
    {
     	$data = $this->where(array('aid'=>$aid))->field('file_url,category_cid,aid')->find();
     	$cur = D('Category','Logic')->get_one($data['category_cid']);
     	$remark = strtolower($cur['remark']);
     	$article = include 'Data/Config/article.inc.php';

     	if($data['file_url'])
     	{
     		$fileUrl = str_replace('.html', '', $data['file_url']);
     		$fileUrl = str_replace('/', '\/', $fileUrl);
 			$article[$aid]= array(
 				'/^'.$fileUrl.'$/'=>"Home/$remark/view?cid={$data['category_cid']}&aid={$data['aid']}",
 			);

     	}
     	else
     	{
     		if(isset($article[$aid]))
				unset($article[$aid]);
     	}
		
     	file_put_contents('./Data/Config/article.inc.php', "<?php\n return ".var_export($article,true)."; ");

    }
}